//var serverUrl='http://117.78.6.144:3000/webapp/'
var serverUrl = 'http://localhost:3000/webapp/'
Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}
function alertmessage($scope, msg) {
    $scope.show = true;
    $scope.message = msg;
    $("#testId").fadeIn();

    setTimeout(function () {
        $("#testId").fadeOut();
    }, 3000)
}
function getVal(id) {
    return $('#' + id).val()
}
function loading($ionicLoading){
    $ionicLoading.show({
        template: '努力加载中...',
        noBackdrop:false,               //是否显示背景
        delay:1000,                     //默认延时显示，默认为0
        duration:5000,                   //自动隐藏
        hideOnStateChange:true
    });
}
function forPage($scope,$http,url,nullId){
    var _page = 1;
    $scope.datas = [];
    $scope.isMore = true;
    $scope.loadData = function (page) {
        var _url='';
        if(url.indexOf('?')>0){
            _url=url+'&num='+page
        }else{
            _url=url+'?num='+page
        }
        $http.get(_url
        ).success(function(result){
            if(result.datas.length==0){
                document.getElementById(nullId).style.display='block'
            }else{
                document.getElementById(nullId).style.display='none'
            }
            if (result.page.num == result.page.pageCount) {
                $scope.isMore = false;
            } else {
                $scope.isMore = true;
            }
            var _result = result.datas;
            angular.forEach(_result,function(data){
                $scope.datas.push(data);
            });
        })
            .error(function(){
                $scope.isMore = false;
            })
            .finally(function(){
                _page++;
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
    };
    $scope.refresh = function (){
        $scope.datas = [];
        _page = 1;
        $scope.loadData(_page);
        $scope.$broadcast('scroll.refreshComplete');
    };
    $scope.loadMoreData = function () {
        $scope.loadData(_page);
    }
}
angular.module('starter.controllers', ['angularFileUpload'])
    .controller('welcomeCtrl', function($scope, $state) {

        setTimeout(function(){
            $state.go('login')
        },3000)

    })
    .controller('loginCtrl', function ($scope, $state, $http,$ionicLoading) {


        $scope.loginData = {username:window.localStorage.username,password:window.localStorage.password};
        $scope.doLogin = function () {
            window.localStorage.username=$scope.loginData.username;
            window.localStorage.password=$scope.loginData.password;
            if (!($scope.loginData.username && $scope.loginData.password)) {
                return alertmessage($scope, '用户名和密码不能为空！！！')
            }
            loading($ionicLoading)
            $http.get(serverUrl + 'login?username=' + $scope.loginData.username + '&password=' + $scope.loginData.password
            ).success(function (result) {
                    $ionicLoading.hide();
                    if (result == '1') {
                        alertmessage($scope, '密码错误！！！')
                    } else if (result == '2') {
                        alertmessage($scope, '用户名不存在！！！')
                    } else if (result == '3') {
                        $state.go('app.boxs');
                    }

                }).error(function (result) {
                });

        }
    })
    .controller('boxsCtrl', function ($scope, $http,$ionicViewService) {
        $ionicViewService.clearHistory();
        var url=serverUrl + 'boxs'
        forPage($scope,$http,url,'nullBoxs');
//        $http.get(serverUrl + 'boxs'
//        ).success(function (result) {
//                $scope.datas = result;
//            }).error(function (result) {
//            });
    })
    .controller('boxCtrl', function ($scope, $stateParams, $http,$ionicLoading) {

        loading($ionicLoading)
        $http.get(serverUrl + 'box?box_id=' + $stateParams.box_id
        ).success(function (result) {
                $ionicLoading.hide()
                $scope.data = result;

            }).error(function (result) {
            });
    })
    .controller('costCtrl', function ($scope, $stateParams, $http,$ionicLoading) {

        $scope.doPost = function () {

            for (var inner in $scope.data) {
                var array = ['standard', 'price', 'less', 'lessprice', 'more', 'moreprice']
                if (array.contains(inner)) {
                    if ($scope.data[inner] == '') {
                        return alertmessage($scope, '内容不能为空！！！')
                    }
                    var partten = /^\d+$/;
                    if (!partten.test($scope.data[inner])) {
                        return alertmessage($scope, '填入项必须为整数！！！')
                    }
                }
            }
            if ($scope.data.standard * getVal('timetype') <= $scope.data.less * getVal('lesstimetype')) {
                return alertmessage($scope, '基础时间必须超过小于的时间！！！')
            }
            if ($scope.data.standard * $scope.data.timetype >= $scope.data.more * getVal('moretimetype')) {
                return alertmessage($scope, '大于的时间必须超过基础时间！！！')
            }
            $scope.data.timetype = getVal('timetype');
            $scope.data.lesstimetype = getVal('lesstimetype')
            $scope.data.moretimetype = getVal('moretimetype')
            loading($ionicLoading)
            $http.post(
                    serverUrl + 'cost',
                $scope.data
            ).success(function (result) {
                    $ionicLoading.hide();
                    if (result) {
                        return alertmessage($scope, '修改成功！！！！')
                    }
                })

        }
        loading($ionicLoading)
        $http.get(serverUrl + 'cost?box_id=' + $stateParams.box_id
        ).success(function (result) {
                $ionicLoading.hide();
                result.box_id = $stateParams.box_id;
                $scope.data = result;
            }).error(function (result) {
            });
    })
    .controller('addrCtrl', function ($scope, $location, $state, $stateParams,$http) {
        $scope.state = true;
        $scope.data = {addr: $stateParams.addr ? $stateParams.addr : '天安门'}
//        百度地图javascript
        var map = new BMap.Map("l-map");
        map.centerAndZoom($scope.addr, 16);// 初始化地图,设置中心点坐标和地图级别。

        map.addControl(new BMap.ZoomControl()); //缩放地图
        var scaleControl = new BMap.ScaleControl();
        map.addControl(scaleControl);       //添加比例尺控件
        var myGeo = new BMap.Geocoder();    //地址解析类
        myGeo.getPoint($scope.data.addr, function (uPoint) {
            if (uPoint) {
                $scope.data.lng = uPoint.lng;
                $scope.data.lat = uPoint.lat;
                console.log(uPoint)
                marker1 = new BMap.Marker(uPoint);  //创建标注
                map.addOverlay(marker1);
                infoWindow1 = new BMap.InfoWindow('当前地址：' + $scope.data.addr);
                marker1.addEventListener("click", function () {
                    this.openInfoWindow(infoWindow1);
                });
                map.centerAndZoom(uPoint, 16);
            } else {

            }
        })
//        百度地图end
        $scope.marker = function () {
            map.clearOverlays();        //  清除所有的标注
            myGeo.getPoint($scope.data.addr, function (uPoint) {
                if (uPoint) {
                    $scope.state = true;
                    $scope.data.lng = uPoint.lng;
                    $scope.data.lat = uPoint.lat
                    console.log(uPoint)
                    marker1 = new BMap.Marker(uPoint);  //创建标注
                    map.addOverlay(marker1);
                    infoWindow1 = new BMap.InfoWindow('当前地址：' + $scope.addr);
                    marker1.addEventListener("click", function () {
                        this.openInfoWindow(infoWindow1);
                    });
                    map.centerAndZoom(uPoint, 16);
                } else {
                    $scope.state = false;
                    return alertmessage($scope, '地址为未知地址，请重新输入')
                }
            })
        }
        $scope.submit = function () {
            if (!$scope.data.addr) {
                return alertmessage($scope, '地址不能为空！！')
            }
            if (!$scope.state) {
                return alertmessage($scope, '地址为未知地址，请重新输入')
            }
//            loading($ionicLoading)
            $scope.data.box_id = $stateParams.box_id;
            $http.post(serverUrl + 'addr', $scope.data
            ).success(function (result) {
//                    $ionicLoading.hide();
//                    alertmessage($scope,'地址修改成功')
                    $location.path('/app/box/' + $scope.data.box_id)

                }).error(function (result) {

                });
        }


    })
    .controller('doorStateCtrl', function ($ionicPopup,$scope, $stateParams, $http,$ionicLoading,$rootScope,$state) {
        $scope.sellGoods=function(index){
            var param={
                doorDatas:$scope.data.doors[index-1],
                box_id:$scope.data.box_id

            }
//            console.log(param)
            window.localStorage.param=JSON.stringify(param)
//            $rootScope.param=param
            $state.go('app.sellGoods')
        }
//        $scope.openAll = function () {
//            loading($ionicLoading)
//            $http.get(serverUrl + 'doorState?index=all&box_id=' + $stateParams.box_id + '&doorsnum=' + $scope.data.doors.length
//            ).success(function (result) {
//                    alertmessage($scope,'操作成功')
//                    $ionicLoading.hide();
//                    $scope.data.doors.forEach(function (door, index) {
//                        door.empty = true;
//                    })
//                }).error(function (result) {
//                });
//        }
        $scope.openAll = function () {
            var confirmPopup = $ionicPopup.confirm({
                title: '打开确认',
                template: '你确定全部打开吗?',
                cancelText: '取消',
                okText: '确定'
            });
            confirmPopup.then(function (res) {
                if (res) {
//                    var param={
//                        index:index,
//                        box_id:$stateParams.box_id
//                    }
//                    if($scope.data.doors[index-1].gid){
//                        param.gid=$scope.data.doors[index-1].gid._id
//                    }
                    loading($ionicLoading)
                    $http.get(serverUrl + 'doorState?index=all&box_id=' + $stateParams.box_id + '&doorsnum=' + $scope.data.doors.length
                    ).success(function (result) {
                            alertmessage($scope,'操作成功')
                            $ionicLoading.hide();
                            $scope.data.doors.forEach(function (door, index) {
                                door.empty = true;
                            })
                        }).error(function (result) {
                        });
                } else {
                    console.log('You are not sure');
                }
            });
        };
        $scope.openOne = function (index) {
            var confirmPopup = $ionicPopup.confirm({
                title: '打开确认',
                template: '你确定打开吗?',
                cancelText: '取消',
                okText: '确定'
            });
            confirmPopup.then(function (res) {
                if (res) {
                    var param={
                        index:index,
                        box_id:$stateParams.box_id
                    }
                    if($scope.data.doors[index-1].gid){
                        param.gid=$scope.data.doors[index-1].gid._id
                    }
                    loading($ionicLoading)
                    $http.get(serverUrl + 'doorState?index='+param.index+'&box_id='+param.box_id+(param.gid?'&gid='+param.gid:'')
                    ).success(function (result) {
                            alertmessage($scope,'操作成功')
                            $ionicLoading.hide();
                            $scope.data.doors.forEach(function (door, i) {
                                if (i + 1 == index) {
                                    door.empty = true
                                }
                            })
                        }).error(function (result) {
                        });
                } else {
                    console.log('You are not sure');
                }
            });
        };

//        $scope.model = [
//            {
//                id: 0,
//                word: '出租'
//            },
//            {
//                id: 1,
//                word: '展售'
//            }
//        ];
        $scope.useSet = function (index) {

            console.log(document.getElementById('aid'+index).checked)
            if (!$scope.data.doors[index-1].empty) {
                alertmessage($scope, '该格子已经被占用，请在空闲状态下再试！！！')
                //变为修改前的值
                document.getElementById('aid'+index).checked=!document.getElementById('aid'+index).checked
                return;
            }
            var use=0;
            if(document.getElementById('aid'+index).checked){
                use=1;
            }
            loading($ionicLoading)
            $http.get(serverUrl + 'useSet?box_id=' + $stateParams.box_id + '&index=' + index + '&use=' + use
            ).success(function (result) {
                    $ionicLoading.hide();
                    $scope.data.doors[index-1].use=use;
                    return alertmessage($scope, '修改成功！！！')
                }).error(function (result) {

                })

//            if (!empty) {
//                alertmessage($scope, '该格子已经被占用，请在空闲状态下再试！！！')
//                //变为修改前的值
//                if($scope.data.doors[index-1].use.id==0){
//                    $scope.data.doors[index-1].use=$scope.model[1]
//                }else{
//                    $scope.data.doors[index-1].use=$scope.model[0]
//                }
//                return;
//            }
//            loading($ionicLoading)
//            $http.get(serverUrl + 'useSet?box_id=' + $stateParams.box_id + '&index=' + index + '&use=' + $scope.data.doors[index - 1].use.id
//            ).success(function (result) {
//                    $ionicLoading.hide();
//                    return alertmessage($scope, '修改成功！！！')
//                }).error(function (result) {
//
//                })

        }
        loading($ionicLoading)
        $http.get(serverUrl + 'doorState?index=0&box_id=' + $stateParams.box_id
        ).success(function (result) {
                $ionicLoading.hide();

//                result.doors.forEach(function (door, index) {
//                    door.use = $scope.model[door.use];
//                })
                console.log(result)
                var row = [];
                for (var i = 1; i <= result.layout.row; i++) {
                    row.push(i)
                }
                var column = [];
                for (var i = 1; i <= result.layout.column; i++) {
                    column.push(i)
                }
                result.layout.rows = row;
                result.layout.columns = column

                var wid = {width: 12 * result.layout.column + 'px'}
                $scope.wid = wid;

                result.box_id = $stateParams.box_id;
                $scope.data = result;

            }).error(function (result) {

            });

    })
    .controller('faultCtrl', function ($scope, $http) {
        var url=serverUrl + 'fault'
        forPage($scope,$http,url,'nullFault');
//        $http.get(serverUrl + 'fault'
//        ).success(function (result) {
//                $ionicLoading.hide();
//                console.log(result)
//                $scope.datas = result;
//            }).error(function (result) {
//
//            })
    })
    .controller('storeCtrl', function ($scope, $http, $ionicPopup,$ionicLoading) {
        $scope.data = {name: ''};

        $scope.showConfirm = function (id, index) {
            var confirmPopup = $ionicPopup.confirm({
                title: '删除确认',
                template: '你确定删除吗?',
                cancelText: '取消',
                okText: '确定'
            });
            confirmPopup.then(function (res) {
                if (res) {
                    if($scope.datas[index].number==0){
                        loading($ionicLoading)
                        $http.get(serverUrl + 'delCategory?id=' + id
                        ).success(function (result) {
                                $ionicLoading.hide()
                                alertmessage($scope, '删除成功！！！');
                                var url=serverUrl + 'category'
                                forPage($scope,$http,url,'nullStore');
//                                $scope.datas.splice(index, 1)
                            }).error(function (result) {

                            })
                    }else{
                        alertmessage($scope,'当前分类下存在商品，请删除商品再试')
                    }


                } else {
                    console.log('You are not sure');
                }
            });
        };

        $scope.showPopup = function (id, index) {
            $scope.data.name = $scope.datas[index].name;
            var myPopup = $ionicPopup.show({
                template: '<input type="text" ng-model="data.name" placeholder="请输入分类名称">',
                title: '名称修改',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>修改</b>',
                        type: 'button-positive',
                        onTap: function (e) {
                            if (!$scope.data.name) {
                                //don't allow the user to close unless he enters wifi password
                                return '1'
                            } else {
                                return $scope.data.name;
                            }
                        }
                    }
                ]
            });
            myPopup.then(function (res) {
                if (res) {
                    if (res == '1') {
                        return alertmessage($scope, '名称不能为空！！')
                    }
                    if (res.length > 5 || res.length < 2) {
                        return alertmessage($scope, '名称长度为2~5个字符！！')
                    }
                    for (var i = 0; i < $scope.datas.length; i++) {
                        if ($scope.datas[i].name.trim() == res.trim()) {
                            return alertmessage($scope, '该分组已存在！！')
                        }
                    }
                    loading($ionicLoading)
                    $http.post(serverUrl + 'updCategory?id=' + id, $scope.data
                    ).success(function (result) {
                            $ionicLoading.hide();
                            alertmessage($scope, '修改成功！！！');
                            $scope.datas[index].name = res;
                        }).error(function (result) {

                        })

                } else {

                }
            });
        };
        $scope.add = function (id, index) {
            var myPopup = $ionicPopup.show({
                template: '<input type="text" ng-model="data.name" placeholder="请输入分类名称">',
                title: '分类添加',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>确定</b>',
                        type: 'button-positive',
                        onTap: function (e) {
                            if (!$scope.data.name) {
                                //don't allow the user to close unless he enters wifi password
                                return '1'
                            } else {
                                return $scope.data.name;
                            }
                        }
                    }
                ]
            });
            myPopup.then(function (res) {
                if (res) {
                    if (res == '1') {
                        return alertmessage($scope, '名称不能为空！！')
                    }
                    if (res.length > 5 || res.length < 2) {
                        return alertmessage($scope, '名称长度为2~5个字符！！')
                    }
                    for (var i = 0; i < $scope.datas.length; i++) {
                        if ($scope.datas[i].name.trim() == res.trim()) {
                            return alertmessage($scope, '该分组已存在！！')
                        }
                    }
                    loading($ionicLoading)
                    $http.post(serverUrl + 'addCategory', $scope.data
                    ).success(function (result) {
                            $ionicLoading.hide();
                            alertmessage($scope, '添加成功！！')
                            var url=serverUrl + 'category'
                            forPage($scope,$http,url,'nullStore');
                        }).error(function () {

                        })

                } else {

                }
            });
        };
//        $scope.add = function () {
//            $("#add").attr("style", "display:block;")
//        }
//        $scope.cancel = function () {
//            $("#add").attr("style", "display:none;");
//        }
//        $scope.submit = function () {
//            if ($scope.data.name == '') {
//                return alertmessage($scope, '分类名称不能为空！！')
//            }
//            if ($scope.data.name.length > 5 || $scope.data.name.length < 2) {
//                return alertmessage($scope, '名称长度为2~5个字符！！')
//            }
//            for (var i = 0; i < $scope.datas.length; i++) {
//                if ($scope.datas[i].name.trim() == $scope.data.name.trim()) {
//                    return alertmessage($scope, '该分组已存在！！')
//                }
//            }
//            $("#add").attr("style", "display:none;");
//
//            loading($ionicLoading)
//            $http.post(serverUrl + 'addCategory', $scope.data
//            ).success(function (result) {
//                    $ionicLoading.hide();
//                    alertmessage($scope, '添加成功！！')
//                    var url=serverUrl + 'category'
//                    forPage($scope,$http,url);
////                    $http.get(serverUrl + 'category'
////                    ).success(function (result) {
////                            $scope.datas = result;
////                        }).error(function (result) {
////
////                        })
//                }).error(function () {
//
//                })
//
//        }
        var url=serverUrl + 'category'
        forPage($scope,$http,url,'nullStore');
//        $http.get(serverUrl + 'category'
//        ).success(function (result) {
//                $ionicLoading.hide();
//                console.log(result)
//                $scope.datas = result;
//            }).error(function (result) {
//
//            })
    })
    .controller('goodsCtrl', function ($scope, $http, $stateParams,$ionicLoading) {
        $scope.gid = $stateParams.gid
        var url=serverUrl + 'showGoods?gid='+$stateParams.gid
        forPage($scope,$http,url,'nullGoods');
//        $http.get(serverUrl + 'showGoods?gid='+$stateParams.gid
//        ).success(function (result) {
//                $ionicLoading.hide();
//                $scope.datas=result;
//            }).error(function (result) {
//            })
    })
    .controller('addGoodsCtrl', function ($scope, $state,$http, $upload,$stateParams,$ionicActionSheet,$ionicLoading) {
        $scope.data = {gid:$stateParams.gid}
        $scope.submit = function () {
            if(!$scope.data.sort){
                return alertmessage($scope,'请填写商品类别')
            }
            if(!$scope.data.name){
                return alertmessage($scope,'请填写商品名称')
            }
            if(!$scope.data.price){
                return alertmessage($scope,'请填写商品价格')
            }
            var partten = /^\d+$/;
            if((!partten.test($scope.data.price))||$scope.data.price<0){
                return alertmessage($scope,'商品价格只能为大于0的数字')
            }
            if(!$scope.data.imgData){
                return alertmessage($scope,'请上传商品图片')
            }
            loading($ionicLoading)
            $http.post(serverUrl + 'addGoods',$scope.data
                ).success(function (result) {
                    $ionicLoading.hide();
                        $state.go('app.goods',{gid:$stateParams.gid})
                    }).error(function (result) {
                    })
        }
        // "添加附件"Event
        $scope.addAttachment = function() {
            for (var i = 1; i <= 10; i++) {
                var p = angular.element(document.querySelector('#nspopover-' + i ));
                p.css('display', 'none');
            }
            $ionicActionSheet.show({
                buttons: [
                    { text: '相机' },
                    { text: '图库' }
                ],
                cancelText: '关闭',
                cancel: function() {
                    return true;
                },
                buttonClicked: function(index) {
                    if(index==0){
                         getPhoto(1)         //调用照相机
                    }else{
                        getPhoto(0)  //调用相册
                    }

                }
            });
        }
         function getPhoto(index) {
            navigator.camera.getPicture(function(imgData){
                var image = document.getElementById('myImage');
                image.src = "data:image/jpeg;base64," + imgData;
                $scope.data.imgData=imgData;
            },function(err){

            },{
                quality:100,                //保存图像的质量 100为完整的
                destinationType: Camera.DestinationType.DATA_URL ,
                //设置success中回调的数据类型  DATA_URL：base64数据  FILE_URL：文件路径
                sourceType : index,         //设置图片的来源   0：图片库 1：照相机
                //====关键设置=======================================
                allowEdit:true, //出现裁剪框
                mediaType:Camera.MediaType.PICTURE,  //允许选择只有照片
                targetWidth:320,//图片裁剪高度
                targetHeight:320 //图片裁剪高度
            })
        }
    })
    .controller('goodsParCtrl', function ($scope, $stateParams,$http,$ionicPopup,$state,$ionicLoading) {
        $scope.showConfirm = function () {
            var confirmPopup = $ionicPopup.confirm({
                title: '删除确认',
                template: '你确定删除吗?',
                cancelText: '取消',
                okText: '确定'
            });
            confirmPopup.then(function (res) {
                if (res) {
                    if($scope.data.sellNum==0){
                        loading($ionicLoading)
                        $http.get(serverUrl + 'delGoods?id=' + $scope.data._id+'&gid='+$scope.data.category
                        ).success(function (result) {
                                $ionicLoading.hide();
                                alertmessage($scope, '删除成功！！！');
                                $state.go('app.goods',{gid:$scope.data.category})
                            }).error(function (result) {

                            })
                    }else{
                        alertmessage($scope,'当前商品正在售卖中，取消售卖后再试！！！')
                    }
                } else {
                    console.log('You are not sure');
                }
            });
        };
        loading($ionicLoading)
        $http.get(serverUrl + 'goodsPar?id='+$stateParams.id
        ).success(function (result) {
                $ionicLoading.hide();
                $scope.data=result;
                console.log(result)
            }).error(function (result) {
            })

    })
    .controller('changGoodsCtrl', function ($scope, $state,$http, $upload,$stateParams,$ionicActionSheet,$ionicLoading) {
        $scope.data={}
        loading($ionicLoading)
        $http.get(serverUrl + 'goodsPar?id=' + $stateParams.id
        ).success(function (result) {
                $ionicLoading.hide();
                $scope.data = result;
            }).error(function (result) {
            });
        $scope.submit = function () {
            if(!$scope.data.sort){
                return alertmessage($scope,'请填写商品类别')
            }
            if(!$scope.data.name){
                return alertmessage($scope,'请填写商品名称')
            }
            if(!$scope.data.price){
                return alertmessage($scope,'请填写商品价格')
            }
            var partten = /^\d+$/;
            if((!partten.test($scope.data.price))||$scope.data.price<0){
                return alertmessage($scope,'商品价格只能为大于0的数字')
            }
            if(!$scope.data.imgData){
                return alertmessage($scope,'请上传商品图片')
            }
            loading($ionicLoading)
            $http.post(serverUrl + 'changGoods',$scope.data
            ).success(function (result) {
                    $ionicLoading.hide();
                    $state.go('app.goodsPar',{id:$scope.data._id})
                }).error(function (result) {
                })
        }
        // "添加附件"Event
        $scope.addAttachment = function() {
            for (var i = 1; i <= 10; i++) {
                var p = angular.element(document.querySelector('#nspopover-' + i ));
                p.css('display', 'none');
            }
            $ionicActionSheet.show({
                buttons: [
                    { text: '相机' },
                    { text: '图库' }
                ],
                cancelText: '关闭',
                cancel: function() {
                    return true;
                },
                buttonClicked: function(index) {
                    if(index==0){
                        getPhoto(1)         //调用照相机
                    }else{
                        getPhoto(0)  //调用相册
                    }

                }
            });
        }
        function getPhoto(index) {
            navigator.camera.getPicture(function(imgData){
                var image = document.getElementById('myImage');
                image.src = "data:image/jpeg;base64," + imgData;
                $scope.data.imgData=imgData;
            },function(err){

            },{
                quality:100,                //保存图像的质量 100为完整的
                destinationType: Camera.DestinationType.DATA_URL ,
                //设置success中回调的数据类型  DATA_URL：base64数据  FILE_URL：文件路径
                sourceType : index,         //设置图片的来源   0：图片库 1：照相机
                //====关键设置=======================================
                allowEdit:true, //出现裁剪框
                mediaType:Camera.MediaType.PICTURE,  //允许选择只有照片
                targetWidth:320,//图片裁剪高度
                targetHeight:320 //图片裁剪高度
            })
        }
    })
    .controller('centerCtrl', function ($ionicModal,$rootScope,$scope, $http,$ionicLoading,$ionicPopup,$location,$timeout,$state) {
        $scope.updateApp = function () {
            $ionicLoading.show({
                template: '正在检查...'
            });
            $timeout(function(){
                $ionicLoading.show({
                    template: '当前已经是最新版本'
                });
                $timeout(function(){
                    $ionicLoading.hide();
                },2000);
            },3000)

        };
        var showConfirm = function() {
            var confirmPopup = $ionicPopup.confirm({
                title: '退出系统?',
                template: '你确定要退出吗?',
                cancelText:'取消',
                okText:'确定'
            });
            confirmPopup.then(function(res) {
                if(res) {
                    ionic.Platform.exitApp();
                } else {
                    console.log('You are not sure');
                }
            });
        };
        $scope.exit = function () {
            showConfirm();
        }
        $scope.loginOut=function(){
            var confirmPopup = $ionicPopup.confirm({
                title: '注销用户?',
                template: '你确定要注销吗?',
                cancelText:'取消',
                okText:'确定'
            });
            confirmPopup.then(function(res) {
                if(res) {
                    $state.go('login')
                } else {
                    console.log('You are not sure');
                }
            });
        }
        $ionicModal.fromTemplateUrl('templates/modal.html',
            function(modal) {
                $rootScope.settingsModal = modal;
            });
        $scope.showModal = function() {
            $rootScope.settingsModal.show();
        };



    })
    .controller('chatboxCtrl', function ($rootScope,$scope, $http,$ionicLoading) {
        $scope.data={};
        $scope.chang=function(){
            if($scope.data.mpassword!=window.localStorage.password){
                return alertmessage($scope,'原密码输入不正确，请重新输入');
            }
            if(!$scope.data.password){
                return alertmessage($scope,'新密码不能为空');
            }
            if($scope.data.password.length<6){
                return alertmessage($scope,'新密码必须为6位数以上的密码');
            }
            if($scope.data.password!=$scope.data.repassword){
                return alertmessage($scope,'2次输入密码不一致');
            }
            loading($ionicLoading)
            $http.get(serverUrl + 'changPassword?password='+$scope.data.password
            ).success(function (result) {
                    $ionicLoading.hide();
                    alertmessage($scope,'修改成功')
                    setTimeout(function(){
                        $rootScope.settingsModal.hide();
                    },3000)
                }).error(function (result) {
                })
        }
        $scope.closeModal = function() {
            $rootScope.settingsModal.hide();
        };
    })
    .controller('sellGoodsCtrl', function ($scope, $http,$ionicLoading,$ionicPopup) {
        $scope.data=JSON.parse(window.localStorage.param)
        $scope.showConfirm = function () {
            var confirmPopup = $ionicPopup.confirm({
                title: '取消售卖确认',
                template: '你确定取消吗?',
                cancelText: '取消',
                okText: '确定'
            });
            confirmPopup.then(function (res) {
                if (res) {

                    loading($ionicLoading)
                    $http.post(serverUrl + 'cancelSell',$scope.data
                    ).success(function (result) {
                            window.localStorage.param=JSON.stringify(result)
                            $scope.data=result
                            $ionicLoading.hide();
                            alertmessage($scope, '取消售卖成功！！！');

                        }).error(function (result) {

                        })



                } else {
                    console.log('You are not sure');
                }
            });
        };

    })
    .controller('sellStoreCtrl', function ($scope, $http, $ionicPopup,$ionicLoading) {
        var url=serverUrl + 'category'
        forPage($scope,$http,url,'nullStore');
    })
    .controller('selectGoodsCtrl', function ($scope, $http, $stateParams,$ionicLoading) {
        $scope.gid = $stateParams.gid
        var url=serverUrl + 'showGoods?gid='+$stateParams.gid
        forPage($scope,$http,url,'nullGoods');
    })
    .controller('sellGoodsParCtrl', function ($scope, $stateParams,$http,$ionicPopup,$state,$ionicLoading) {
        $scope.select=function(){
            var param={
                gid:$scope.data._id,
                boxDatas:JSON.parse(window.localStorage.param)
            }
            if(!param.boxDatas.doorDatas.empty){
                if(param.gid==param.boxDatas.doorDatas.gid._id){
                    return alertmessage($scope,'当前售卖商品已经为该商品')
                }
            }
            loading($ionicLoading)
            $http.post(serverUrl + 'sellGoods',param
            ).success(function (result) {
                    $ionicLoading.hide();
                    alertmessage($scope,'售卖成功')
                    setTimeout(function(){
                        window.localStorage.param=JSON.stringify(result)
                        $state.go('app.sellGoods')
                    },1000)
                }).error(function (result) {
                })
        }

        loading($ionicLoading)
        $http.get(serverUrl + 'goodsPar?id='+$stateParams.id
        ).success(function (result) {
                $ionicLoading.hide();
                $scope.data=result;
            }).error(function (result) {
            })

    })
    .controller('AppCtrl', function ($scope, $http) {

    })

    .controller('PlaylistsCtrl', function ($scope) {
        $scope.playlists = [
            { title: 'Reggae', id: 1 },
            { title: 'Chill', id: 2 },
            { title: 'Dubstep', id: 3 },
            { title: 'Indie', id: 4 },
            { title: 'Rap', id: 5 },
            { title: 'Cowbell', id: 6 }
        ];
    })

    .controller('PlaylistCtrl', function ($scope, $stateParams) {
    });

